package com.uroad.liaoningpos.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.boc.aidl.printer.AidlPrinter;
import com.newland.aidl.scanner.AidlScanner;
import com.newland.aidl.scanner.AidlScannerListener;
import com.newland.aidl.scanner.ScannerCode;
import com.ums.AppHelper;
import com.uroad.liaoningpos.R;
import com.uroad.liaoningpos.common.BaseActivity;
import com.uroad.liaoningpos.common.CurrApplication;
import com.uroad.liaoningpos.common.GlobalData;
import com.uroad.liaoningpos.common.PrintServiceResult;
import com.uroad.liaoningpos.common.SPContants;
import com.uroad.liaoningpos.model.MemInfo;
import com.uroad.liaoningpos.model.PayResultMDL;
import com.uroad.liaoningpos.model.TransData;
import com.uroad.liaoningpos.service.DeviceService;
import com.uroad.liaoningpos.util.BitmapUtil;
import com.uroad.liaoningpos.util.SPUtils;
import com.uroad.liaoningpos.webService.PosWS;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.file.SDUtil;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.util.sys.SystemUtil;
import com.uroad.lib.widget.dialog.DialogHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @创建者 wlw
 * @创建时间 2019/4/2 16:32
 * @描述 收银台
 */
public class CheckoutCounterActivity extends BaseActivity {
    private static String TAG = "CheckoutCounterActivity";
    @BindView(R.id.etAmount)
    EditText etAmount;
    @BindView(R.id.tvScanQRcode)
    TextView tvScanQRcode;
    @BindView(R.id.tvSwipeCard)
    TextView tvSwipeCard;
    @BindView(R.id.llPrintInfo)
    LinearLayout llPrintInfo;

    @BindView(R.id.ivLogo)
    ImageView ivLogo;
    @BindView(R.id.tvTitleType)
    TextView tvTitleType;
    @BindView(R.id.tvMerchantName)
    TextView tvMerchantName;
    @BindView(R.id.tvMerchantNo)
    TextView tvMerchantNo;
    @BindView(R.id.tvTerminalNo)
    TextView tvTerminalNo;
    @BindView(R.id.tvTraceNo)
    TextView tvTraceNo;
    @BindView(R.id.tvBatchNo)
    TextView tvBatchNo;
    @BindView(R.id.tvRefNo)
    TextView tvRefNo;
    @BindView(R.id.tvDateTime)
    TextView tvDateTime;
    @BindView(R.id.tvAmt)
    TextView tvAmt;
    @BindView(R.id.tvPayNo)
    TextView tvPayNo;
    @BindView(R.id.tvChannelName)
    TextView tvChannelName;
    @BindView(R.id.tvTransNo)
    TextView tvTransNo;
    @BindView(R.id.tvOrderNo)
    TextView tvOrderNo;
    @BindView(R.id.tvDiscountInfo)
    TextView tvDiscountInfo;
    @BindView(R.id.tvPrintType)
    TextView tvPrintType;

    @BindView(R.id.tvPayUnionCard)
    TextView tvPayUnionCard;
    @BindView(R.id.tvPayAliPay)
    TextView tvPayAliPay;
    @BindView(R.id.tvPayWechat)
    TextView tvPayWechat;
    @BindView(R.id.tvPayUnionScan)
    TextView tvPayUnionScan;

    private static int PAYTYPE_UNION_SWIPE = 1;
    private static int PAYTYPE_UNION_SCAN = 2;
    private static int PAYTYPE_HIGHTWAY_CODE = 3;
    private static int PAYTYPE_WECHAT = 4;
    private static int PAYTYPE_ALIPAY = 5;

    //支付金额
    private String amount;
    //支付类型 刷卡 扫码
    private int type;
    private String channelId = "";
    //流水号
    private String voucherNo = "";
    //唯一序列号
    private String posimei = "";
    private String beonduty = "";
    private TransData transData;
    private int printCount = 0;
    private String path = "";
    private AidlPrinter printerModule;
    private String outOrderNo = "";
    private String insertid = "";
    private String merchantno = "";
    private String merchantnozl = "";
    private String merchantname = "";
    private String terminalno = "";
    private String terminalnozl = "";
    private AidlScanner iScanner;
    private String payCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayout(R.layout.activity_checkout_counter);
        ButterKnife.bind(this);
        setTitle("收银台");
        initData();
        initListener();
        //打开软键盘
        bindDeviceService();
    }

    private void initData() {
        iScanner = DeviceService.getScanner();
        posimei = (String) SPUtils.get(this, SPContants.SP_IMEI, "");
        beonduty = (String) SPUtils.get(this, SPContants.SP_BEONDUTY, "");
        merchantno = (String) SPUtils.get(this, SPContants.SP_MERCHANTNO, "");
        merchantnozl = (String) SPUtils.get(this, SPContants.SP_MERCHANTNO_ZHILIAN, "");
        merchantname = (String) SPUtils.get(this, SPContants.SP_MERCHANTNAME, "");
        terminalno = (String) SPUtils.get(this, SPContants.SP_TERMINALNO, "");
        terminalnozl = (String) SPUtils.get(this, SPContants.SP_TERMINALNO_ZHILIAN, "");
        //小数点过滤 防止首位小数点或小数点后面超过两位
        etAmount.addTextChangedListener(watcher);
        etAmount.setOnKeyListener(keyListener);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isFinishing()) {
                    SystemUtil.openSoftKeyboard(CheckoutCounterActivity.this, etAmount);
                }
            }
        }, 800);

    }

    private void initListener() {
        //edittext 软键盘监听
        etAmount.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (actionId) {
                    //软键盘完成按钮
                    case EditorInfo.IME_ACTION_DONE:
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        break;
                    default:
                }
                return true;
            }
        });
    }
    private void initScan() {
        try {
            //---------初始化接口可不调用，特殊需求才需要调用-----------//
            Bundle bundle = new Bundle();
            bundle.putBoolean(ScannerCode.ScanParams.IS_ONCE, true);
//            bundle.putBoolean(ScannerCode.ScanParams.IS_FRONT,false);
//            bundle.putBoolean(ScannerCode.ScanParams.IS_REAR,false);
            iScanner.initScan(bundle);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void bindDeviceServiceSuccess() {
        super.bindDeviceServiceSuccess();
        try {
            printerModule = AidlPrinter.Stub.asInterface(deviceService.getPrinter());
        } catch (RemoteException e) {
            e.printStackTrace();
            LogUtil.i(TAG, "获取打印模块异常");
        }
    }

    @OnClick({R.id.tvScanQRcode, R.id.tvSwipeCard,R.id.tvPayUnionCard,R.id.tvPayAliPay,R.id.tvPayWechat,
            R.id.tvPayUnionScan, R.id.etAmount})
    public void selectPayType(View view) {
        String money = etAmount.getText().toString().trim();
        if (TextUtils.isEmpty(money) || "0.".equals(money)) {
            showShortToast("请输入收款金额");
            return;
        }
        double moneyD = Double.parseDouble(money) * 100;
        if (moneyD <= 0) {
            showShortToast("收款金额为0,请重新输入");
            return;
        }
        long amout= (long) moneyD;
        amount = String.valueOf(amout);
        if (amount.length() < 12) {
            int len = 12 - amount.length();
            for (int i = 0; i < len; i++) {
                amount = "0" + amount;
            }
        }

        switch (view.getId()) {
            case R.id.tvScanQRcode:
                //扫码支付
                scanCode("unionscan");
                break;
            case R.id.etAmount:
                etAmount.setSelection(etAmount.getText().length());
                break;
            case R.id.tvSwipeCard:
                //刷卡支付
                swipeCard();
                break;
            case R.id.tvPayUnionCard:
                type = PAYTYPE_UNION_SWIPE;
                channelId = "acquire";
                getOrder();
                //刷卡支付
                //                swipeCard();

                break;
            case R.id.tvPayAliPay:
                type = PAYTYPE_ALIPAY;
                break;
            case R.id.tvPayWechat:
                type = PAYTYPE_WECHAT;
                break;
            case R.id.tvPayUnionScan:

                startScan();
                type = PAYTYPE_UNION_SCAN;
               /* channelId = "unionscan";
                getOrder();*/

                //扫码支付
                //                scanCode("unionscan");
                break;
        }
    }

    private void startScan(){
        try {
            iScanner.startScan(ScannerCode.ScanType.FRONT,30,new AidlScannerListener.Stub(){

                @Override
                public void onScanResult(String barcode) throws RemoteException {
                    payCode = barcode;
                    getOrderType(barcode);
                    showShortToast(barcode);
                }

                @Override
                public void onTimeout() throws RemoteException {


                }

                @Override
                public void onError(int errorCode, String detail) throws RemoteException {


                }

                @Override
                public void onCancel() throws RemoteException {


                }
            });
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    private void getOrderType(String barcode) {
        DialogHelper.showLoading(this,"正在下单");
        doRequest(PosWS.getcodetype, PosWS.getcodetypeParams(amount, type + "", beonduty, barcode), PosWS.getcodetype);
    }
    private void getOrder() {
        DialogHelper.showLoading(this,"正在下单");
        doRequest(PosWS.payorder, PosWS.payorderParams(amount, type + "", beonduty), PosWS.payorder);
    }

    /**
     * 扫码
     */
    private void scanCode(String channelId) {
        DialogHelper.showLoading(this, "开始扫码");
        startPay("cardPay","89");
        //startPay("", "", channelId);
    }

    /**
     * 刷卡支付
     */
    private void swipeCard() {
        DialogHelper.showLoading(this, "开始刷卡");
        startPay("cardPay","101");
        //startPay("","","acquire");
    }

    private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");


    private void startPay(String channelName, String tranType) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.yada.spos.cashierplatfrom",
                "com.yada.spos.cashierplatfrom.InvokeActivity"));
       /* intent.setPackage(GlobalData.YADA_PKG);
        intent.setAction(GlobalData.YADA_CLASS);*/
      /*  if ("acquire".equals(channelId)) {
            intent.setAction(GlobalData.YADA_CLASS);
        }else{
            intent.setAction(GlobalData.YADA_CLASS_SCAN);
        }*/
       /* //中行直连参数
        intent.putExtra("transType", 2);
        intent.putExtra("operatorNo", "");
        intent.putExtra("amount", amount);
        intent.putExtra("outOrderNo", outOrderNo);
        intent.putExtra("channelId", channelId);
        intent.putExtra("remark", "");
        intent.putExtra("payCode", "");
        intent.putExtra("insertSale", false);
        intent.putExtra("rfForcePsw", false);*/

        //中行间连参数
        intent.putExtra("channelName", channelName);
        intent.putExtra("tranType", tranType);
        intent.putExtra("offerFlag", "0");
        intent.putExtra("packageName", getPackageName());
        intent.putExtra("actionName", "");
        Date date = new Date();
        intent.putExtra("appOrderNo", format.format(date) + amount);
        intent.putExtra("tranAmt", amount);
        intent.putExtra("pointsNum", "");

        startActivityForResult(intent, 0);
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String temp = s.toString();
            int posDot = temp.indexOf(".");
            if (posDot < 0)
                return;
            //输入以 " . "开头的情况，自动在.前面补0
            if (temp.startsWith(".") && posDot == 0) {
                s.insert(0, "0");
                return;
            }
            //输入"08" 等类似情况
            if (temp.startsWith("0") && temp.length() > 1 && (posDot == -1 || posDot > 1)) {
                s.delete(0, 1);
                return;
            }
            //小数点后面只能有两位小数
            if (temp.length() - posDot - 1 > 2) {
                s.delete(posDot + 3, posDot + 4);
            }

        }
    };

    private View.OnKeyListener keyListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                /*if (etAmount.getText().length() > 1) {
                    etAmount.setSelection(etAmount.getText().length());
                    etAmount.setText(etAmount.getText().toString()
                            .substring(0, etAmount.getText().length() - 1));
                }else{
                    etAmount.setText("");
                }*/
            }
            return false;
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        DialogHelper.endLoading();
        if (data != null) {
            switch (resultCode) {
                case 0://间连交易失败
                    Bundle bundle1 = data.getExtras();
                    if (bundle1 != null) {
                        String reason = bundle1.getString("msg");
                        if (reason != null) {
                            showShortToast(reason);
                            LogUtil.i("wlw", "支付结果回调：" + reason);
                            payerror(reason);
                        }
                    }
                    break;
                case 1://间连交易成功
//                    String payresult = data.getStringExtra("result");
//                    if (!TextUtils.isEmpty(payresult)) {
                        getPayInfo(data);
//                    }
                    break;
                case -1:
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        transData = new TransData();
                        transData.setMerchantName(bundle.getString("merchantName"));//终端名称
                        transData.setMerchantNo(bundle.getString("merchantId"));//商户号
                        transData.setTerminalNo(bundle.getString("terminalId"));//终端号
                        transData.setCardIssuerId(bundle.getString("iisCode"));//发卡行id
                        transData.setCardIssuerCode(bundle.getString("iisName"));//发卡行名称
                        transData.setCardAcquirerCode(bundle.getString("acqName"));//收单行名称
                        transData.setCardAcquirerId(bundle.getString("acqCode"));//收单行名称
                        transData.setPayType(type + "");
                        transData.setRefNo(bundle.getString("referenceNo"));//参考号
                        transData.setOperNo("01");
                        transData.setInsertid(insertid);
                        transData.setOrderno(outOrderNo);
                        String date = bundle.getString("transTime");//20190522154757
                        if (!TextUtils.isEmpty(date) && date.length() > 10) {
                            String year = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
                            String day = date.substring(8, 10) + ":" + date.substring(10, 12) + ":" + date.substring(12);
                            transData.setDate(year);
                            transData.setTime(day);
                        }

                        transData.setTransType(bundle.getInt("transType") + "");//交易类型
                        transData.setResponseCode(bundle.getString("responseCode"));//支付结果
                        transData.setMessage(bundle.getString("message"));//支付信息
                        transData.setAmount(bundle.getLong("amount") + "");//原交易金额
                        transData.setTransAmount(bundle.getLong("transAmount") + "");//实际交易金额
                        transData.setTransTime(bundle.getString("transTime"));//交易时间
                        transData.setCardNo(bundle.getString("cardNo"));//卡号
                        transData.setTraceNo(bundle.getString("voucherNo"));//流水号
                        transData.setVoucherNo(bundle.getString("payOrderNo"));//扫码订单号
                        transData.setBatchNo(bundle.getString("batchNo"));//批次号
                        transData.setOutOrderNo(bundle.getString("outOrderNo"));//外部订单号
                        transData.setReferenceNo(bundle.getString("referenceNo"));//系统参考号
                        transData.setChannelId(bundle.getString("channelId"));//渠道
                        transData.setCardInputMode(bundle.getString("cardInputMode"));//用卡方式
                        transData.setPeriods(bundle.getInt("periods") + "");//分期期数
                        transData.setCurrencyCode(bundle.getString("currencyCode"));//货币类型
                        transData.setCardAttribute(bundle.getString("cardAttribute"));//银行卡属性
                        transData.setInterOrg(bundle.getString("interOrg"));//卡组织
                        transData.setAcqCode(bundle.getString("acqCode"));//收单行标识码
                        transData.setAcqName(bundle.getString("acqName"));//收单行
                        transData.setIisCode(bundle.getString("iisCode"));//发卡行标识码
                        transData.setIisName(bundle.getString("iisName"));//发卡行
                        LogUtil.i(TAG,"支付返回数据："+transData.toString());
                        if ("00".equals(transData.getResponseCode())) {
                            pay();
                        }else {
                            String reason = bundle.getString("message");
                            if (reason != null) {
                                showShortToast(reason);
                                LogUtil.i("wlw", "支付结果回调：" + reason);
                                payerror(reason);
                            }
                        }
                    }
            }
        }
        //
        //        if (AppHelper.TRANS_REQUEST_CODE == requestCode) {
        //            LogUtil.d(TAG, "resultCode" + resultCode);
        //            if (Activity.RESULT_OK == resultCode) {
        //                if (null != data) {
        //                    Log.i(TAG, "requestCode----->" + requestCode + "\nresultCode----->" + resultCode + "\ndata Extra(result)" + data.getStringExtra("result"));
        //                    getPayResult(data);
        //                } else {
        //                    LogUtil.i(TAG, "Intent is null" + "\n");
        //                }
        //            } else {
        //                LogUtil.i(TAG, "resultCode is not RESULT_OK" + "\n");
        //            }
        //        }else if(-1 == resultCode){
        //            if (printCount == 1) {
        //                DialogHelper.showLoading(this,"正在打印中");
        //                startPrint();
        //            }else {
        //                showPrintResult(data.getStringExtra("resultCode") + "");
        //            }
        //            LogUtil.d("LOG", data.getStringExtra("resultCode")+"");//具体的code见ServiceResult
        //        }
    }

    private void payerror(String reason) {
        if (type==PAYTYPE_HIGHTWAY_CODE){
            doRequest(PosWS.payerr, PosWS.payerrParams(insertid, outOrderNo, reason,
                    merchantnozl, merchantname, terminalnozl, beonduty), PosWS.payerr);
        }else {
            doRequest(PosWS.payerr, PosWS.payerrParams(insertid, outOrderNo, reason,
                    merchantno, merchantname, terminalno, beonduty), PosWS.payerr);
        }
    }

    private void getPayInfo(Intent data) {
        Bundle bundle = data.getExtras();
        if (bundle != null) {
            LogUtil.i("wlw", "支付结果回调：" + bundle.toString());
            transData = new TransData();
            transData.setMerchantName(bundle.getString("merchantName"));//终端名称
            transData.setMerchantNo(bundle.getString("merchantId"));//商户号
            transData.setTerminalNo(bundle.getString("terminalId"));//终端号
            transData.setCardIssuerId(bundle.getString("iisCode"));//发卡行id
            transData.setCardIssuerCode(bundle.getString("issue"));//发卡行名称
            transData.setCardAcquirerCode(bundle.getString("acqName"));//收单行名称
            transData.setCardAcquirerId(bundle.getString("acqCode"));//收单行编号
            transData.setPayType(type + "");//支付类型
            transData.setRefNo(bundle.getString("referNo"));//参考号
            transData.setOperNo("01");
            transData.setInsertid(insertid);
            transData.setOrderno(outOrderNo);
            String date = bundle.getString("tranDateTime");//20190522154757 交易日期
            if (!TextUtils.isEmpty(date) && date.length() >= 10) {
                Calendar calendar = Calendar.getInstance();
                date = calendar.get(Calendar.YEAR) + date;
                String year = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
                String day = date.substring(8, 10) + ":" + date.substring(10, 12) + ":" + date.substring(12);
                transData.setDate(year);
                transData.setTime(day);
            }

            transData.setTransType(bundle.getInt("transType") + "");//交易类型
            transData.setResponseCode(bundle.getString("responseCode"));//支付结果
            transData.setMessage(bundle.getString("message"));//支付信息
            transData.setAmount(bundle.getLong("amount") + "");//原交易金额
            transData.setTransAmount(bundle.getLong("transAmount") + "");//实际交易金额
            transData.setTransTime(bundle.getString("tranDateTime"));//交易时间
            transData.setCardNo(bundle.getString("cardNo"));//卡号
            transData.setTraceNo(bundle.getString("traceNo"));//流水号
            transData.setVoucherNo(bundle.getString("payVoucherNum"));//扫码订单号/付款凭证号
            transData.setBatchNo(bundle.getString("batchNo"));//批次号
            transData.setOutOrderNo(bundle.getString("appOrderNo"));//外部订单号
            transData.setReferenceNo(bundle.getString("referenceNo"));//系统参考号
            transData.setChannelId(bundle.getString("channelId"));//渠道
            transData.setCardInputMode(bundle.getString("cardInputMode"));//用卡方式
            transData.setPeriods(bundle.getInt("periods") + "");//分期期数
            transData.setCurrencyCode(bundle.getString("currencyCode"));//货币类型
            transData.setCardAttribute(bundle.getString("cardAttribute"));//银行卡属性
            transData.setInterOrg(bundle.getString("interOrg"));//卡组织
            transData.setAcqCode(bundle.getString("acqCode"));//收单行标识码
            transData.setAcqName(bundle.getString("acqName"));//收单行
            transData.setIisCode(bundle.getString("iisCode"));//发卡行标识码
            transData.setIisName(bundle.getString("iisName"));//发卡行
            LogUtil.i(TAG,"支付返回数据："+transData.toString());
//            if ("00".equals(transData.getResponseCode())) {
                pay();
//            }
        }
    }

    private void getPayResult(Intent data) {
        StringBuilder result = new StringBuilder();
        Map<String, String> map = AppHelper.filterTransResult(data);
        result.append("{\"" + AppHelper.TRANS_APP_NAME + "\":\"" + map.get(AppHelper.TRANS_APP_NAME) + "\",");
        result.append("\"" + AppHelper.TRANS_BIZ_ID + "\":\"" + map.get(AppHelper.TRANS_BIZ_ID) + "\",");
        result.append("\"" + AppHelper.RESULT_CODE + "\":\"" + map.get(AppHelper.RESULT_CODE) + "\",");
        result.append("\"" + AppHelper.RESULT_MSG + "\":\"" + map.get(AppHelper.RESULT_MSG) + "\",");
        result.append("\"" + AppHelper.TRANS_DATA + "\":" + map.get(AppHelper.TRANS_DATA) + "}");

        Log.i(TAG, "Activity调用 result = " + result.toString());
        if (null != result) {
            String json = result.toString();
            //            json = json.replaceAll("\\\\", "");
            //                json = result.substring(result.indexOf("{"));
            PayResultMDL resultMDL = FastJsonUtils.parseObjectJSON(json, PayResultMDL.class);
            if (resultMDL != null) {
                transData = resultMDL.getTransData();
                if ("00".equals(transData.getResCode())) {
                    transData.setAmount(amount+"");
                    //TODO 银商调用3.1.6.支付接口
                    //                    if ("scan".equalsIgnoreCase(type)) {
                    //                        getPayType();
                    //                    } else if ("swipe".equalsIgnoreCase(type)) {
                    //                        transData.setPayType("1");
                    //                        pay();
                    //                    }
                } else {
                    showLongToast(resultMDL.getTransData().getResDesc());
                }
            }
        }
    }

    private void getPayType() {
        doRequest(PosWS.payno, PosWS.paynoParams(transData.getPayNo()), PosWS.payno);
    }

    private void pay() {
        //        DialogHelper.showLoading(this, "正在提交");
        doRequest(PosWS.pay, PosWS.payParams(amount+"", transData.getMerchantNo(),
                transData.getMerchantName(),transData.getTerminalNo(),
                transData.getBatchNo(), transData.getTraceNo(),
                transData.getRefNo(), transData.getTransChnName(),
                transData.getCardIssuerCode(), transData.getCardIssuerId(),
                transData.getCardAcquirerCode(), transData.getCardAcquirerId(),
                transData.getDate(), transData.getTime(), transData.getMemInfo(),
                transData.getCardNo(), transData.getPayType(), transData.getOperNo(),
                posimei,beonduty,transData.getVoucherNo(),insertid,outOrderNo), PosWS.pay);
    }

    private void codePay(String channelId){
//        String codeAmount= String.format("%012d", amount);
        String str = "payment://com.newland.pospp/payment?channelId="+channelId+"&outOrderNo="+outOrderNo+
                "&amount="+amount+"&payCode="+payCode;
//        if("scan".equals(channelId)&&type == PAYTYPE_UNION_SCAN)
//            str = str+"&remark=银联码";
//        else if("directscan".equals(channelId))
//            str = str+"&remark=高速码";
        Uri uri = Uri.parse(str);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivityForResult(intent, 1);
    }

    @Override
    public void OnHttpTaskComplete(String result, String id) {
        super.OnHttpTaskComplete(result, id);
        try {
            JSONObject jsonObject = new JSONObject(result);
            String status = jsonObject.getString("status");
            if ("00".equalsIgnoreCase(status)) {
                if (PosWS.pay.equalsIgnoreCase(id)) {
                    showShortToast("交易成功");
                    etAmount.setText("");
                } else if (PosWS.payorder.equalsIgnoreCase(id)) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    outOrderNo = data.getString("orderno");
                    insertid = data.getString("insertid");
                    if (!TextUtils.isEmpty(outOrderNo) && !TextUtils.isEmpty(insertid)) {
                        //下单完成 开始支付
                        DialogHelper.showLoading(this, "开始支付");
                        if (type == PAYTYPE_UNION_SCAN) {
                            scanCode("unionscan");
                        } else if (type==PAYTYPE_UNION_SWIPE){
//                            swipeCard();
                            codePay("boc");
                        }else if (type == PAYTYPE_ALIPAY) {
                        } else if (type == PAYTYPE_WECHAT) {
                        }
                    }
                } else if (PosWS.payerr.equalsIgnoreCase(id)) {
                    LogUtil.i(TAG, "错误信息提交成功");
                } else if (PosWS.payno.equalsIgnoreCase(id)) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (data != null) {
                        String payType = data.getString("type");
                        if (!TextUtils.isEmpty(payType)) {
                            transData.setPayType(payType);
                            pay();
                            print(payType);
                        }
                    }
                }else if (PosWS.getcodetype.equalsIgnoreCase(id)) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    outOrderNo = data.getString("orderno");
                    insertid = data.getString("insertid");
                    type = data.getInt("type");
                    if (type == PAYTYPE_UNION_SCAN||type == PAYTYPE_ALIPAY||type == PAYTYPE_WECHAT) {
                        codePay("scan");
                    } else if (type==PAYTYPE_HIGHTWAY_CODE){
                        codePay("directscan");
                    }
                }
            }else{
                showShortToast(jsonObject.getString("msg"));
                if (PosWS.pay.equalsIgnoreCase(id)) {
                    CurrApplication.daoUtils.insert(transData);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void print(String payType) {
        MemInfo memInfo = FastJsonUtils.parseObjectJSON(transData.getMemInfo(), MemInfo.class);
        //        llPrintInfo.setVisibility(View.VISIBLE);
        if ("2".equalsIgnoreCase(payType)) {
            //银联码
            ivLogo.setVisibility(View.GONE);
            tvTitleType.setText("银联商务签购单");
            tvChannelName.setText("渠道商名称:银联二维码");
        } else if ("3".equalsIgnoreCase(payType)) {
            //高速码
            ivLogo.setVisibility(View.VISIBLE);
            tvTitleType.setText("辽高收单签购单");
            tvChannelName.setText("渠道商名称:高速通二维码");
        }
        tvMerchantName.setText("商户名称:"+transData.getMerchantName());
        tvMerchantNo.setText("商户编号:"+transData.getMerchantNo());
        tvTerminalNo.setText("终端编号:" + transData.getTerminalNo());
        tvTraceNo.setText("凭证号:" + transData.getTraceNo());
        tvBatchNo.setText("批次号:" + transData.getBatchNo());
        tvRefNo.setText("参考号:" + transData.getRefNo());
        tvDateTime.setText("交易日期:" + transData.getDate()+transData.getTime());
        tvAmt.setText("金额:RMB " + transData.getAmt());
        tvPayNo.setText("付款码:" + transData.getPayNo());
        tvTransNo.setText("交易号:" + memInfo.getTransNo());
        tvOrderNo.setText("订单号:" + memInfo.getOrderNo());
        tvDiscountInfo.setText("第三方优惠说明:" + memInfo.getDiscountInfo());
        DialogHelper.showLoading(this,"正在打印中");
        startPrint();
    }

    private void startPrint() {
        if (printCount == 0) {
            printCount++;
            tvPrintType.setText("商户存根");
        } else if (printCount == 1) {
            printCount = 0;
            tvPrintType.setText("持卡人存根");
        }
        ViewTreeObserver observer = llPrintInfo.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                llPrintInfo.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                path = BitmapUtil.viewSaveToImage(llPrintInfo, SDUtil.createDir("LiaoNingPos"), "print.PNG",true);
                //TODO 重打印
                if (SDUtil.isExistSD()) {
                    //view转bitmap并保存在本地
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            AppHelper.callPrint(CheckoutCounterActivity.this, path);
                        }
                    }).start();
                }else{
                    showShortToast("打印失败，未检测到存储设备");
                }
            }
        });
    }

    @Override
    public void OnHttpFailure(String id) {
        super.OnHttpFailure(id);
        if (PosWS.pay.equalsIgnoreCase(id)) {
            CurrApplication.daoUtils.insert(transData);
            showShortToast("订单上传失败，请联系维护人员");
        }
    }

    @Override
    public void OnHttpNetWork(String id) {
        super.OnHttpNetWork(id);
        if (PosWS.pay.equalsIgnoreCase(id)) {
            CurrApplication.daoUtils.insert(transData);
        }
    }
    private void showPrintResult(String resultCode) {
        if (!TextUtils.isEmpty(resultCode)) {
            String result = PrintServiceResult.getResult(resultCode);
            showShortToast(result);
        }
    }
}
